package com.eistert.java.algorithm.template;

/**
 * @Description: binary search unrecursion implementation code
 * @Author: ai
 * @create: 2023-04-17 22:42
 */
public class BinarySearchNonRecursionTemplate {

    public static void main(String[] args) {
        int[] arr = new int[]{1, 3, 8, 10, 11, 67, 100};
        int index = binarySearch(arr, 11);
        System.out.println("index=" + index);
    }

    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (arr[mid] == target) {
                return mid;
            }

            if (arr[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }

        return -1;

    }
}
